package com.yoki.cloud.common.tenant;

import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.yoki.cloud.common.core.GlobalConst;

import javax.annotation.PostConstruct;
import java.util.List;

@Configuration
@ConditionalOnBean(SqlSessionFactory.class)
@AutoConfigureAfter(PageHelperAutoConfiguration.class)
public class MybatisTenantInterceptorAutoConfig {
    private static final Logger logger = LoggerFactory.getLogger(MybatisTenantInterceptorAutoConfig.class);

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @PostConstruct
    public void addPageInterceptor() {
        MybatisTenantInterceptor interceptor = new MybatisTenantInterceptor();
        interceptor.setProperties(null);
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
        }
    }

    @Bean
    public RequestInterceptor headerInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes();
                String tenantFlag = attributes.getRequest().getHeader(GlobalConst.HEADER_TENANT_FLAG);
                logger.info("add feign header:tenantFlag=" + tenantFlag);
                requestTemplate.header(GlobalConst.HEADER_TENANT_FLAG, tenantFlag);
            }
        };
    }
}
